package ex3;

import common.IRunnable;
import common.Utils;
import ex2.ITokenizer;
import ex2.JflexTokenizer;
import ex2.Token;
import ex2.grammars.GrammarFactory;
import ex2.grammars.GrammarType;
import ex2.grammars.IGrammar;
import fun.parser.Tree;
import ic.ast.Node;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 12/6/13
 */
public abstract class Ex3Runnable implements IRunnable {

    /**
     * Creates ast from given filename (.ic)
     * @param filename ic source filename
     * @param grammarType grammar type to use
     * @return built ast
     * @throws Exception
     */
    protected Node getAst(String filename, GrammarType grammarType) throws Exception {
        ITokenizer tokenizer = new JflexTokenizer();
        List<Token> tokens = tokenizer.tokenize(Utils.fileToString(filename));
        IGrammar grammar = GrammarFactory.createGrammar(grammarType);
        Tree parseTree = grammar.constructParseTree(tokens);
        return grammar.constructAst(parseTree);
    }
}
